<?php

//套装
namespace App\Http\Controllers\Admin\Mall;


use App\Enums\MallEnum;
use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Response\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SuitController extends BaseController
{
    /**
     * @api {Get} /mall/suit/list 套装列表
     *
     * @apiGroup 个性商城-单品管理
     *
     * @apiParam {Int} is_rarity 是否稀有商品：-1（默认）：不限制；1：是；0：否
     * @apiParam {Int} is_recommend 是否推荐商品：-1（默认）：不限制；1：是；0：否
     * @apiParam {Int} style_id 风格标签id，0：不限制，其它的根据接口
     * @apiParam {Int} days 天数
     * @apiParam {String} name 商品名称
     * @apiParam {Int} status 出售状态：-1：不限制（默认）；1：上架；0：下架
     * @apiParam {String} add_date 添加日期，YYYY-mm-dd
     * @apiParam {Int} original_price 原始价格
     * @apiParam {Int} price 套装价格
     * @apiParam {Int} page_size 每页显示条数
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 358, 序号
    "product_name": "套装A", 商品名称
    "category_id": 7,
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/bcee3870de2cffa0591522282989ea56x5QnD.png", 图片
    "special": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/bcee3870de2cffa0591522282989ea56x5QnD.png",
    "on_sale": 1,
    "rarity": 0,
    "is_activity": 0,
    "add_time": "2021-05-18 13:21:20", 添加时间
    "update_time": "1970-01-01 08:00:00", 更新时间
    "style": "", 风格
    "status_name": "上架", 销售状态
    "product_price": [ 商品价格信息
    {
    "day": 7, 天数
    "original_price": 120 原价
    "price": 100 现价
    },
    {
    "day": 15,
    "original_price": 250 原价
    "price": 200
    }
    ],
    "suit_products": [ 套装包含的商品信息：
    {
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/c0de0f8aea46a81f770c29f4d5bd8f67C3PKL.png" 图片
    },
    {
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/2b40590558c0c6e704b222d32f7c0e7dstSsE.png"
    },
    {
    "picture": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/newadmin/192efab1858823d6d78c3bc5e1a9cbeanBEKB.png"
    }
    ]
    }
    ],
    "first_page_url": "http://local.qipaoadmin/mall/suit/list?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/mall/suit/list?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/mall/suit/list",
    "per_page": 10,
    "prev_page_url": null,
    "to": 2,
    "total": 2
    }
    }
     */
    public function list(Request $request)
    {
        $param = $request->all();
        $v = app('validator')->make($param, [
            'is_rarity' => 'integer|in:-1,0,1',
            'is_recommend' => 'integer|in:-1,0,1',
            'style_id' => 'integer|min:0',
            'days' => 'integer|min:0',
            'name' => 'string',
            'status' => 'integer|in:-1,0,1',
            'add_date' => 'date',
            'original_price' => 'integer',
            'price' => 'integer',
            'page_size' => 'integer|min:1',
        ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $param['group'] = 2; //套装

        return Response::sendData(app('repo_mall_products')->getList($param));
    }

    /**
     * @api {Post} /mall/suit/add 添加套装
     *
     * @apiGroup 个性商城-单品管理
     *
     * @apiParam {String} suit_name 套装名称，必须
     * @apiParam {String} suit_desc 套装介绍，必须
     * @apiParam {String} picture 套装封面图，必须
     * @apiParam {String} style_ids 风格id，多个用英文逗号连接，必须
     * @apiParam {String} product_ids 套装包含的商品id，多个用英文逗号连接，必须
     * @apiParam {String} days_price 套装天数与价格信息，天数1:价格1;天数2:价格2...必须
     * @apiParam {Int} rarity_tag_id 稀有度标签id，0：无稀有度标签；其它根据接口
     * @apiParam {Int} sale_status 出售状态：1：上架；0：下架，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function add(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'suit_name' => 'required|string|max:10',
                'suit_desc' => 'required|string|max:100',
                'picture' => 'required|url',
                'style_ids' => 'required|string',
                'product_ids' => 'required|string',
                'days_price' => 'required|string',
                'rarity_tag_id' => 'required|integer|min:0',
                'sale_status' => 'required|integer|in:0,1',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        return app('repo_mall_products')->addOrEditSuit($request->all());
    }

    /**
     * @api {Get} /mall/suit/detail 查看套装详情
     *
     * @apiGroup 个性商城-单品管理
     *
     * @apiParam {String} id 套装id，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "id": 376,
    "suit_name": "国庆特惠套装5", 套装名称
    "suit_desc": "国庆节大回馈，6折套装", 套装介绍
    "picture": "http://picture.jpg", 图片
    "on_sale": 1, 销售状态：1：上架中；2：已下架
    "suit_product_info": [ 套装包含的商品信息：
    {
    "id": 362, 商品id
    "product_name": "赤兔", 商品名称
    "picture": "http://picture.jpg", 图片
    "product_prices": [ 商品价格信息：
    {
    "day": 7, 天数
    "price": 100 价格
    },
    {
    "day": 15,
    "price": 200
    },
    {
    "day": 30,
    "price": 400
    }
    ]
    },
    {
    "id": 363,
    "product_name": "的卢",
    "picture": "http://picture.jpg",
    "product_prices": [
    {
    "day": 7,
    "price": 100
    },
    {
    "day": 15,
    "price": 200
    },
    {
    "day": 30,
    "price": 400
    }
    ]
    }
    ],
    "suit_style_ids": [ 套装风格id：
    1,
    2,
    3
    ],
    "suit_price_info": [ 套装价格信息：
    {
    "day": 7, 天数
    "price": 100, 套装现价
    "original_price": 200 套装原价
    },
    {
    "day": 15,
    "price": 200,
    "original_price": 400
    }
    ]
    }
    }
     */
    public function detail(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $id = $request->id;

        $suit = app('model_mall_products')
            ->select('id', 'title as suit_name', 'desc as suit_desc', 'picture', 'on_sale', 'rarity_tag_id')
            ->where('id', $id)
            ->first();
        if (empty($suit)) throw new BasicException(0, '套装不存在');

        //查询套装包含的商品
        $productIds = app('model_mall_products_suit_relation')->where('suit_id', $id)->pluck('product_id');
        $suitProducts = app('model_mall_products')
            ->select('id', 'title as product_name', 'picture')
            ->whereIn('id', $productIds)->get();
        foreach ($suitProducts as &$suitProduct) {
            $suitProduct->product_prices = app('model_mall_products_price')
                ->select('day', 'price')->where('product_id', $suitProduct->id)->get();
        }
        $suit->suit_product_info = $suitProducts;
        //查询套装的风格
        $suit->suit_style_ids = app('model_product_style_join')->select('style_id')->where('product_id', $id)->pluck('style_id');
        //查询套装的天数与价格信息
        $suit->suit_price_info = app('model_mall_products_price')->select('day', 'price', 'original_price')->where('product_id', $id)->get();

        return Response::sendData($suit);
    }

    /**
     * @api {Put} /mall/suit/edit 编辑套装
     *
     * @apiGroup 个性商城-单品管理
     *
     * @apiParam {Int} id 套装id，必须
     * @apiParam {String} suit_name 套装名称，必须
     * @apiParam {String} suit_desc 套装介绍，必须
     * @apiParam {String} picture 套装封面图，必须
     * @apiParam {String} style_ids 风格id，多个用英文逗号连接，必须
     * @apiParam {String} product_ids 套装包含的商品id，多个用英文逗号连接，必须
     * @apiParam {String} days_price 套装天数与价格信息，天数1:价格1;天数2:价格2...必须
     * @apiParam {Int} rarity_tag_id 稀有度标签id，0：无稀有度标签；其它根据接口
     * @apiParam {Int} sale_status 出售状态：1：上架；0：下架，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function edit(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'suit_name' => 'required|string|max:10',
                'suit_desc' => 'required|string|max:100',
                'picture' => 'required|url',
                'style_ids' => 'required|string',
                'product_ids' => 'required|string',
                'days_price' => 'required|string',
                'rarity_tag_id' => 'required|integer|min:0',
                'sale_status' => 'required|integer|in:0,1',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $suit = app('model_mall_products')->select('id')->where('id', $request->id)->first();
        if (empty($suit)) throw new BasicException(0, '套装不存在');

        return app('repo_mall_products')->addOrEditSuit($request->all());
    }

    /**
     * @api {Delete} /mall/suit/del 删除套装
     *
     * @apiGroup 个性商城-单品管理
     *
     * @apiParam {String} ids 套装id，多个用英文逗号连接，必须
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function del(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'ids' => 'required|string',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $ids = trim($request->ids, ',');
        $ids = explode(',', $ids);

        DB::beginTransaction();
        try {
            //删除套装
            $suits = app('model_mall_products')->select('title')->whereIn('id', $ids)->get();
            foreach ($suits as $suit) {
                if ($suit->on_sale == 1) throw new BasicException(0, "上架状态的套装不能删除：{$suit->title}");
            }
            app('model_mall_products')->whereIn('id', $ids)->delete();
            //删除套装与商品的关联
            app('model_mall_products_suit_relation')->whereIn('suit_id', $ids)->delete();
            //删除套装价格
            app('model_mall_products_price')->whereIn('product_id', $ids)->delete();
            //删除套装与风格标签的关联
            app('model_product_style_join')->whereIn('product_id', $ids)->delete();
            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }
}